package com.yuanjiu.common.util;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

public class HtpClientUtils {
	

	public static synchronized String getCommentByPage(String url) throws ClientProtocolException, IOException{
		
		HttpClient httpClient=HttpClients.createDefault();
		
		HttpGet httpGet=new HttpGet(url);
		HttpResponse response = httpClient.execute(httpGet);
		 
		return  EntityUtils.toString(response.getEntity());
		
	}
	
	public static synchronized String doGet(String url){
		
		HttpClient httpClient=HttpClients.createDefault();
		HttpGet httpGet=new HttpGet(url);
		HttpResponse response;
		try {
			response = httpClient.execute(httpGet);
			return  EntityUtils.toString(response.getEntity());
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public static synchronized String doPost(String url,Map<String, String> map){
		HttpClient httpClient=HttpClients.createDefault();
		HttpPost httpPost=new HttpPost(url);
		httpPost.setProtocolVersion(HttpVersion.HTTP_1_0);
		httpPost.addHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_CLOSE);
		List<NameValuePair> params=new ArrayList<NameValuePair>();
		//建立一个NameValuePair数组，用于存储欲传送的参数
		for(Map.Entry<String, String> tmp:map.entrySet()){
			params.add(new BasicNameValuePair(tmp.getKey(),tmp.getValue()));
		}
		
		//添加参数
		try {
			httpPost.setEntity(new UrlEncodedFormEntity(params));
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		HttpResponse response;
		try {
			response = httpClient.execute(httpPost);
			return  EntityUtils.toString(response.getEntity());
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	public static void main(String[] args){
//		String reString = null;
//		reString = doGet("https://www.1919.cn/product/commentData?productCode=1013195&productId=366329680322105344&page=1&vendorId=346840538491785216");
//		System.out.println(reString);
		String priceUrl="http://www.jiuxian.com/pro/selectProActByProId.htm";
		Map<String,String> map=new HashMap<String,String>();
		map.put("proId", "21624");
		String result=HtpClientUtils.doPost(priceUrl, map);
		System.out.println("result"+result);
	}
}
